const router = require("koa-router")();
const fs = require("fs");
const path = require("path");
const Help = require('../help.js');
const mongo_models = require('../mongo/mongo_models.js');
router.prefix("/task");

function Get_Page(pagenum=1,pagesize=10,skip=0){
  if(pagesize==0){}
  else{
    pagesize=pagesize>0?pagesize:10
  }
  let options={
    pagenum,
    pagesize,
  }
  pagenum=pagenum>0?pagenum-0:1
  skip=skip>=0?skip-0:0
  
  if(pagenum>1){
    skip=(pagenum?(pagenum-1)*pagesize:0)+skip
  }
  if(skip>=0){
    options.skip = skip
  }
  if(pagesize>0){
    options.limit = pagesize
  }
  return options;
}
function Check_Date (date) {
  try{
    return new Date(date).getTime() > 0
  }
  catch{
    return false
  }
}
function Condition_Date (parmar) {
  let lst_error_msg="";
  let condition=undefined
  let start=parmar.start
  let end=parmar.end
  let parmar_object={}
  if(Check_Date(start)){
    parmar_object["$gte"]=(new Date(start)).getTime()
  }
  if(Check_Date(end)){
    parmar_object["$lte"]=(new Date(end)).getTime()
  }
  if(JSON.stringify(parmar_object) !="{}"){
    condition=parmar_object
  }
  else{
    lst_error_msg=`time 参数设置无效`
  }
  return {
    condition,
    lst_error_msg
  }
}
async function search_record (pamars) {
  let {id,code,region,state,remark,name,time,pagenum,pagesize}=pamars
  let options=Get_Page(pagenum-0,pagesize-0,0)
  let conditions={}
  if(id){
    conditions["id"]={ 
      $regex:id,
      $options:"i"
    }
  }
  if(code){
    conditions["code"]=={ 
      $regex:code,
      $options:"i"
    }
  }
  if(region){
    conditions["region"]={ 
      $regex:region,
      $options:"i"
    }
  }
  if(state){
    conditions["state"]=state
  }
  if(remark){
    conditions["remark"]={ 
      $regex:remark,
      $options:"i"
    }
  }
  if(name){
    conditions["name"]={ 
      $regex:name,
      $options:"i"
    }
  }
  if(time){
    if(typeof time==="string"){
      time=JSON.parse(time)
    }
    let time_Date=Condition_Date(time)
    if(time_Date.condition){
      conditions["time"]=time_Date.condition
    }
  }
  let projection={
    '_id': 0,
    '__v': 0,
  }
  let Records_Model=mongo_models.Get_Records_Model()
  let count = await Records_Model.countDocuments(conditions);
  let query = await Records_Model.find(conditions,projection,options);
  return {
    data:query,
    page:{
      count:count,
      pagenum:options.pagenum,
      pagesize:options.pagesize,
    }
}
}
router.post('/cb',async (ctx, next)=>{
  let pamars=Help.Get_Pamars(ctx)
  Help.Console_log(`${JSON.stringify(pamars?.result)}`)
  let {type,id,status}=pamars?.result
  if(status=="success"){
    if(type=="exe"){
      let exe_back=await Help.Request_Get_Common(`${global["json_config"]?.gp_url}/task/get_exetask?`,{
        exeid:id,
      },0)
      if(exe_back?.status){
        let exe_reuslt=exe_back?.result
        let exe_reuslt_type=exe_reuslt?.type
        let exe_reuslt_data=exe_reuslt?.data
        let tif_result=exe_reuslt_data?.result
        let tif_result_xml="";
        if(exe_reuslt_data?.xmloptions?.xml_from && exe_reuslt_data?.xmloptions?.xml_to){
          tif_result_xml=exe_reuslt_data?.xmloptions?.xml_to
        }
        else if(exe_reuslt_data?.options?.xml_from && exe_reuslt_data?.options?.xml_to){
          tif_result_xml=exe_reuslt_data?.options?.xml_to
        }
        let task_back=await Help.Request_Get_Common(`${global["json_config"]?.gp_url}/task/get_task?`,{
          taskid:exe_reuslt?.taskid,
        },0)
        let task_name=task_back?.result?.name
        if(task_name){
          let produce_result=await mongo_models.GetTasks({
            mongo_id:task_name
          })
          if(produce_result?.length==1){
            let batch=produce_result[0]?.batch
            if(batch){
              let msg={
                type:exe_reuslt_type=="trans"?"cog":"tif",
                result:[tif_result,tif_result_xml],
                batch:batch,
              }
              await Help.add_rabbitmq(msg,"sdp_pri_gp_done");
            }
          }
          else{
            let msg={
              type:exe_reuslt_type=="trans"?"cog":"tif",
              result:[tif_result,tif_result_xml],
              batch:"test_all",
            }
            await Help.add_rabbitmq(msg,"sdp_pri_gp_done");
          }
        }
      }
    }
  }
  //需要返回id 才会撤销消息 不然重复发送
  ctx.response.status = 200;
  ctx.set("Cotnent-Type", "application/json")
  ctx.body ={
    id:pamars?.result?.id
  }
});
router.get('/c_cb',async (ctx, next)=>{
  let pamars=Help.Get_Pamars(ctx)
  let {dir,batch}=pamars
  Help.Console_log(`c_cb ${JSON.stringify(dir)}`)
  let files=Help.Get_Deep_Files(dir,[".tif"],true)
  for (let i = 0; i < files?.length; i++) {
    let result=[]
    let one_file = files[i];
    result.push(one_file?.file)
    let namenoext=one_file?.namenoext
    let xml_file=`${dir}/${namenoext}.xml`
    if(Help.Check_isFile(xml_file)){
      result.push(xml_file)
    }
    if(result?.length>0){
      await Help.add_rabbitmq({
        result:result,
        type:"cog",
        batch:batch,
      },"sdp_pri_gp_done");
    }
  }
  return Help.Resolve(ctx,true,true,'');
});
router.get('/add_task_to_gp',async (ctx, next)=>{
  let pamars=Help.Get_Pamars(ctx)
  let {id}=pamars
  let result=await Help.add_task_do_to_go_from_id(id)
  return Help.Resolve(ctx,true,result,'');
});
router.get('/task',async (ctx, next)=>{
  let pamars=Help.Get_Pamars(ctx)
  let {id}=pamars
  let result=await mongo_models.GetTasks(pamars)
  return Help.Resolve(ctx,true,result,'');
});
router.get('/del_task',async (ctx, next)=>{
  let {id}=Help.Get_Pamars(ctx)
  if(!id){
    Help.Resolve(ctx,true,false,'参数id是必须的') 
    return
  }
  let result=await Help.delete_task(id)
  return Help.Resolve(ctx,true,result,'');
});
router.get('/set_stat',async (ctx, next)=>{
  let {id,state}=Help.Get_Pamars(ctx)
  if(!id){
    Help.Resolve(ctx,true,false,'参数id是必须的') 
    return
  }
  let result=await mongo_models.SetStat(id,state)
  return Help.Resolve(ctx,true,result,'');
});
router.get('/detail',async (ctx, next)=>{
  let pamars=Help.Get_Pamars(ctx)
  let result=await mongo_models.GetDetail(pamars)
  return Help.Resolve(ctx,true,result,'');
});

module.exports = router;